<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\WorkContact\Action\Sidebar;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Call\Logic\RecordIndexLogic;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Contract\CallRecordContract;
use MoChat\App\Sales\Contract\SalesClientTaskContract;
use MoChat\App\Sales\Model\CallRecord;
use Hyperf\Di\Annotation\Inject;
use MoChat\App\User\Model\User;
use MoChat\App\Common\Middleware\SidebarAuthMiddleware;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 呼叫.
 * @Controller
 */
class CallRequest extends AbstractAction
{
    use ValidateSceneTrait;

    public function buildUniqueId()
    {
        $microtime = microtime();
        $microtime = substr($microtime, strpos($microtime, '.') + 1, 6);
        return date("YmdHis") . $microtime . mt_rand(10000000, 99999999);
    }


    /**
     * @Middlewares({
     *    @Middleware(SidebarAuthMiddleware::class)
     * })
     *
     * @RequestMapping(path="/sidebar/workContact/request", methods="POST")
     */
    public function handle()
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        $mobile=Db::table('work_employee')->where('id',$user['id'])->value('mobile');
        if (empty($mobile)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '你暂未设置手机号');
        }
        $data = $this->request->all();
        $this->validated($data);
        //请求外部接口
        $token=$this->post( [
            'Username' => env("CALL_CENTER_USERNAME_CALL"),
            'Password' => env("CALL_CENTER_PASSWORD_CALL"),
        ],env("CALL_CENTER_BASE_URL_CALL").'/api/login', [
            'Content-Type:application/json',
        ]);
        //请求外部接口
        return $this->post( [
            'Callid' => $this->buildUniqueId(),
            'App_id' =>env("CALL_CENTER_USERNAME_CALL"),
            'Caller'=>$data['called']??$mobile,
            'Callee'=>$data['phone'],
            'Cdr_url'=>'http://manage-cop.sczrk.cn/api/dashboard/call/requestRecord',
        ],env("CALL_CENTER_BASE_URL_CALL").'/api/CallRequest', [
            'Content-Type:application/json',
            'Authorization:JH '.$token['token'],
        ]);
    }
    public function post($data, $url,$header)
    {
        $jsonString = json_encode($data, JSON_UNESCAPED_UNICODE + JSON_UNESCAPED_SLASHES);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonString);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        $output = curl_exec($ch);
        return json_decode($output, true);
    }
    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'phone' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'phone.required' => '呼出号码必填',
        ];
    }
}
